﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LocationType = System.UInt16;
using ValueType = System.Int16;

namespace ManoMachine.Common
{
    public class MemoryMap
    {
        readonly Dictionary<LocationType, ValueType> _memory = new Dictionary<LocationType, ValueType>();

        //public void Insert(LocationType location, ValueType value)
        //{
        //    _memory.Add(location, value);
        //}

        //public Nullable<ValueType> GetByAddress(LocationType location)
        //{
        //    return _memory.ContainsKey(location) ? (ValueType?)null : _memory[location];
        //}

        public Nullable<ValueType> this[int index]
        {
            get
            {
                return this[(ushort) index];
            }
            set
            {
                this[(ushort)index] = value;
            }
        }

        public Nullable<ValueType> this[LocationType index]
        {
            get
            {
                return _memory.ContainsKey(index) ? (ValueType?)null : _memory[index];
            }
            set
            {
                if (!_memory.ContainsKey(index))
                {
                    _memory.Add(index, value.GetValueOrDefault());
                }
                else
                {
                    _memory[index] = value.GetValueOrDefault();
                }
            }
        }

        public Dictionary<LocationType, ValueType>.Enumerator GetEnumerator()
        {
            return this._memory.GetEnumerator();
        }

        public void Print()
        {
            ConsoleColor foregroundColor = Console.ForegroundColor;
            bool color = false;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine();
            Console.WriteLine("Memory Map");
            foreach (KeyValuePair<LocationType, ValueType> keyValuePair in _memory)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write(keyValuePair.Key + " : ");
                Console.ForegroundColor = color ? ConsoleColor.White : ConsoleColor.Gray;
                color = !color;
                Console.WriteLine("[{0:X04}]", keyValuePair.Value);
            }
            Console.ForegroundColor = foregroundColor;
        }
    }
}
